package com.bob.web.service.system;

import com.bob.web.common.constant.Page;
import com.bob.web.dao.AdminDao;
import com.bob.web.dao.RoleDao;
import com.bob.web.entity.system.Admin;
import com.bob.web.entity.system.Role;
import com.bob.web.service.BaseService;
import com.bob.web.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 名称: AdminService<br>
 * 描述:<br>
 * 类型: JAVA<br>
 * 最近修改时间:2017/7/20 11:22<br>
 *
 * @author BoYangsh
 * @version [版本号, V1.0]
 * @since 2017/7/20 11:22
 */
//@Service
public class AdminService extends BaseService {

	@Autowired
	private AdminDao adminDao;

	@Autowired
	private RoleDao roleDao;

	public Admin findAdminByName(String username, String...fields) {
		return adminDao.findAdminByUsername(username, fields);
	}

	public Page<Admin> findPage(Page<Admin> page) {
		adminDao.findPage(page);
		return page;
	}

	public void add(Admin user) {
		setAdminRole(user);
		adminDao.add(user);
	}

	public void delete(String id) {
		adminDao.delete(id);
	}

	public void update(Admin user) {
		setAdminRole(user);
		Query query = Query.query(Criteria.where("_id").is(user.getId()));
		Update update = Update.update("name", user.getName()).set("userName", user.getUsername()).set("gender",
				user.getGender()).set("age", user.getAge()).set("phone", user.getPhone()).set("email", user.getEmail())
				.set("address", user.getAddress()).set("roleIds", user.getRoleIds()).set("roleNames", user.getRoleNames());
		adminDao.findAndModify(query, update);
	}

	private void setAdminRole(Admin admin) {
		if(!CollectionUtil.isEmpty(admin.getRoleIds())){
			List<Role> roles = roleDao.findRolesByIds(admin.getRoleIds());
			if(!CollectionUtil.isEmpty(roles)) {
				List<String> roleNames = new ArrayList<>();
				List<Long> roleIds = new ArrayList<>();
				roles.forEach(role -> {
					roleNames.add(role.getName());
					roleIds.add(role.getId());
				});
				admin.setRoleIds(roleIds);
				admin.setRoleNames(roleNames);
			}
		}
	}

	public Admin findUserById(Long id) {
		return adminDao.findUserById(id);
	}
}
